<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入更新人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedTime">
        <el-date-picker
          clearable
          size="small"
          v-model="queryParams.updatedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属应用id" prop="applicationId">
        <el-input
          v-model="queryParams.applicationId"
          placeholder="请输入所属应用id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表单分类" prop="formType">
        <el-select
          v-model="queryParams.formType"
          placeholder="请选择表单分类"
          clearable
          size="small"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lemonPiggy-UDform:page:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lemonPiggy-UDform:page:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lemonPiggy-UDform:page:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lemonPiggy-UDform:page:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updatedBy" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <!-- <el-table-column label="网页代码" align="center" prop="webPageCode" /> -->
      <el-table-column label="所属应用id" align="center" prop="applicationId" />
      <el-table-column
        label="所属应用名称"
        align="center"
        prop="applicationName"
      />
      <!-- <el-table-column label="表单分类" align="center" prop="formType" /> -->
      <!-- <el-table-column label="权限" align="center" prop="authorizeType" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="details(scope.row)"
            >详情</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lemonPiggy-UDform:page:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lemonPiggy-UDform:page:remove']"
            >删除</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-s-tools"
            @click="setRelationship(scope.row)"
            v-hasPermi="['lemonPiggy-UDform:page:remove']"
            >业务关系设置</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改页面自定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="网页代码" prop="webPageCode">
          <el-input
            v-model="form.webPageCode"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="所属应用id" prop="applicationId">
          <el-input
            v-model="form.applicationId"
            placeholder="请输入所属应用id"
          />
        </el-form-item>
        <el-form-item label="表单分类" prop="formType">
          <el-select v-model="form.formType" placeholder="请选择表单分类">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 业务关系设置对话框 -->
    <el-drawer
      direction="rtl"
      :visible.sync="drawer"
      :before-close="handleClose"
    >
    <div slot="title" class="drawerTitle">
      <el-row>
        <el-col :span="10">业务关系设置</el-col>
        <el-col :offset="10" :span="2">
          <el-button type="primary" size="small" round @click="save">保存</el-button>
        </el-col>
      </el-row>
    </div>
      <el-form ref="relationShip" :model="relationShip" label-width="80px">
        <div class="divTitle"><span class="spanTitle">基础设置</span></div>
        <el-form-item label="关系名称">
          <el-input
            v-model="relationShip.name"
            placeholder="请输入关系名称"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="relationShip.state">
            <el-radio label="start">启用</el-radio>
            <el-radio label="closure">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调用源">
          <el-input
            v-model="name"
            disabled
            placeholder="请输入调用源"
          />
        </el-form-item>
        <el-form-item label="关联对象">
          <el-select v-model="associatedObj" placeholder="请选择" @change="associatedObjClick">
            <el-option
              v-for="item in pageAllList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="divTitle"><span class="spanTitle">触发点</span></div>
        <el-form-item label="触发方式">
          <el-radio-group v-model="relationShip.triggerPoint">
            <el-radio label="manual">手动选择</el-radio>
            <el-radio label="automatic">自动关联</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="divTitle"><span class="spanTitle">关系映射</span></div>
      </el-form>
      <!-- 关系映射表 -->
      <template>
        <span style="margin-left: 10px;">新建表关联：</span>
        <el-button
          size="small"
          icon="el-icon-plus"
          @click="copy"
        />
      </template>
      <el-table
        :data="tableData"
        style="width: 100%;margin-top: 10px;"
      >
        <el-table-column :label="name" align="center">
          <template slot-scope="scope" >
            <el-select v-model="scope.row.field" placeholder="请选择">
              <el-option
                v-for="i in scope.row.fieldList"
                :key="i.orderNum"
                :label="i.name"
                :value="i.code"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="setIntentName" align="center">
          <template slot-scope="scope" >
            <el-select v-model="scope.row.intentField" placeholder="请选择">
              <el-option
                v-for="i in scope.row.intentFieldList"
                :key="i.orderNum"
                :label="i.name"
                :value="i.code"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
             <el-button
                size="small"
                icon="el-icon-minus"
                @click="strikeOut(scope.row,scope.$index)"
              />
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import {
  listPage,
  listAllPage,
  getPage,
  delPage,
  addPage,
  updatePage,
  beLinked
} from "@/views/UDform/js/page";
import {getFormField} from '@/views/UDform/js/field'

export default {
  name: "Page",
  data() {
    return {
      tableData:[{
        // 选中目标表字段
        intentField:'',
        // 选中当前表字段
        field:'',
        // 选中目标表所有字段
        intentFieldList:[],
        // 当前表所有字段
        fieldList:[],
      }],
      tableDataCopy:{},
      // 目标表名
      intentName:'',
      // 当前表名
      name:'',
      // 当前表id
      id:'',
      // 选中关联对象
      associatedObj: "",
      // 遮罩层
      drawer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 页面自定义表格数据
      pageList: [],
      // 页面自定义所有表格数据
      pageAllList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      relationShip: {
        // 关系名称
        name: "",
        // 状态
        state: "",
        // 触发方式
        triggerPoint: ""
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        name: null,
        webPageCode: null,
        applicationId: null,
        formType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getAllList();
  },
  activated() {
    this.getList();
  },
  computed:{
    setIntentName:function() {
      return this.intentName == "" ? "请选择关联表":this.intentName;
    }
  },
  methods: {
    /** 查询页面自定义列表 */
    getList() {
      this.loading = true;
      listPage(this.queryParams).then(response => {
        this.pageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllList() {
      listAllPage(this.queryParams).then(response => {
        this.pageAllList = response.data;
      });
    },
    // 复制
    copy() {
      // 解构数据，否则所有的el-table-column的数据都会绑定在一起
      // 等同于JSON.parse(JSON.stringify());
      this.tableDataCopy = ({...this.tableData[0]});
      this.tableDataCopy.field = '';
      this.tableDataCopy.intentField = '';
      this.tableData.push({...this.tableDataCopy})
    },
    // 删除
    strikeOut(row,index) {
      this.tableData.splice(index,1)
    },
    // 字段转json
    fieldInJson(obj){
      let a = [];
      for (const key in obj) {
        let b = {}
        b.value = key;
        b.label = key;
        a.push(b)
      }
      return a;
    },
    // 业务关系设置保存按钮
    save() {
      let obj = {};
      obj.name = this.relationShip.name;
      obj.page = this.associatedObj;
      let arr = [];
      for (let i = 0; i < this.tableData.length; i++) {
        let a = {};
        a[this.tableData[i].field] = this.tableData[i].intentField;
        arr.push(a)
      }
      obj.fieldList = arr;
      let str = JSON.stringify(obj);
      let data = {};
      data.id = this.id;
      data.relationShip = str
      beLinked(data).then((res)=>{
        if (res.code == 200) {
          this.$message.success("保存成功")
        }
      })
    },
    // 关联对象事件
    associatedObjClick() {
      let id = this.associatedObj
      getPage(id).then((res)=>{
        if (res.code == 200) {
          this.intentName = res.data.name
        }
      });
      getFormField(id).then((res)=>{
        if (res.code == 200) {
          let data = res.data
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].intentFieldList = data;
        }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        name: null,
        webPageCode: null,
        applicationId: null,
        formType: null
      };
      this.resetForm("form");
    },
    // 重置业务关系设置界面
    resetDrawer() {
      this.relationShip = {
        name: "",
        state: "",
        transfer: "",
        triggerPoint: ""
      };
      this.associatedObj = "";
      this.intentName = "";
      this.tableData = [{
        // 选中目标表字段
        intentField:'',
        // 选中当前表字段
        field:'',
        // 选中目标表所有字段
        intentFieldList:[],
        // 当前表所有字段
        fieldList:[],
      }];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加页面自定义";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.$router.push({
        name: "LayoutFunction",
        query: {
          pageDataId: id,
          buttonType: false,
          applicationId: row.applicationId,
          id: row.id,
          name: row.name
        }
      });
    },
    /** 详情按钮操作 */
    details(row) {
      let id = row.id;
      getPage(id).then(response => {
        this.form = response.data;
        this.$router.push({
          name: "TemplateList"
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePage(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPage(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除页面自定义编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delPage(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 设置业务关系按钮 */
    setRelationship(row) {
      this.id = row.id;
      getFormField(this.id).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          this.drawer = true;
          this.name = row.name;
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].fieldList = data;
          }
          console.log(this.tableData);
        }
      })
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.resetDrawer();
          done();
        })
        .catch(_ => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "lemonPiggy-UDform/page/export",
        {
          ...this.queryParams
        },
        `lemonPiggy-UDform_page.xlsx`
      );
    }
  }
};
</script>
<style scoped>
.divTitle {
  width: 100%;
  margin-bottom: 20px;
  padding: 2px 0;
  background-color: #95bde5;
}
.spanTitle {
  margin-left: 10px;
  font-size: 16px;
}
.el-row{
   margin-bottom: 10px;
}
</style>
